function openEditAdapterWindow(title) {
    var data 
    if (Ext.getCmp('remoteAdapterGrid').getSelection().length>0 && title!="增加数据适配器") {
        data = Ext.getCmp('remoteAdapterGrid').getSelection()[0].data
    } 
    console.log(data)
    var editWindow = Ext.create('Ext.window.Window', {
        title: title,
        iconCls:'x-fa fa-database',
        width: 1050,
        modal:true,
        items:[
            {
                xtype:'form',
                width:'100%',
                height:'100%',
                border:false,
                items:[
                    {
                        xtype: 'hiddenfield',
                        id:'adapterId',
                        value:data==null?"":data.id
                    },
                    {
                        xtype: 'textfield',
                        id:'adapterName',
                        labelAlign:'left',
                        allowBlank:false,
                        fieldLabel:'适配器名称',
                        value:data==null?"":data.adapter_name
                    },
                    {
                        xtype: 'container',
                        listeners:{
                            render:function() {
                                window.adapterSourceEditor = ace.edit("adapterSourceEditor");
                                window.adapterSourceEditor.setTheme("ace/theme/monokai")
                                window.adapterSourceEditor.setFontSize(20)
                                window.adapterSourceEditor.session.setMode("ace/mode/groovy");
                                window.adapterSourceEditor.on("change", function(value){
                                    
                                })
                                window.adapterSourceEditor.session.setValue(data==null?"":data.adapter_source)
                                
                            }
                        },
                        html:'<div id="adapterSourceEditor" style="width:1038px;height:470px"></div>'
                    },
                    {
                        xtype: 'container',
                        html:'<div id="adapterPreview" style="width:1038px;height:260px"></div>'
                    }
                ],
                buttons: [
                    {
                        xtype: 'button',
                        text: '测试',
                        handler: function() {
                            
                            Ext.Ajax.request({
                                url: "../remoteadapter/testsource",
                                params: {
                                    id: chartId,
                                    url: Ext.getCmp('dataRemoteUrl').getValue(),
                                    adapterSource:window.adapterSourceEditor.session.getValue()
                                },
                                success:function(response, opts) {
                                    var res = Ext.JSON.decode(response.responseText)
                                    console.log(res)
                                    if (res.success) {
                                        if (typeof res.message=="object") {
                                            $('#adapterPreview').html(JSON.stringify(res.message, null, "\t"))
                                        } else {
                                            $('#adapterPreview').html(res.message)
                                        }
                                        
                                    } else {
                                        $('#adapterPreview').html('<font style="color:red" >'+res.message+'<font>')
                                    }
                                    
                                    
                                }
                            })
                            
                        }
                    },
                    {
                        xtype: 'button',
                        text: '取消',
                        handler: function() {
                            editWindow.close()
                        }
                    },
                    {
                         xtype: 'button',
                         text: '确定',
                         handler: function() {

                            var adapterId = Ext.getCmp("adapterId").getValue()
                            var adapterName = Ext.getCmp("adapterName").getValue()
                            nowRemoteAdapterSource = window.adapterSourceEditor.session.getValue()
                            Ext.Ajax.request({
                                url: "../remoteadapter/save",
                                params: {
                                    adapterId:adapterId,
                                    chartId:chartId,
                                    adapterName:adapterName,
                                    adapterSource:window.adapterSourceEditor.session.getValue(),
                                },
                                success:function(response, opts) {
                                    Ext.getCmp('remoteAdapterGrid').getStore().load()
                                    editWindow.close()
                                    
                                }
                            })

                           
                         }
                    }
                ]
            }
        ]
    })
    editWindow.show()
}

function updateDataSource() {
   
    var sqlDsContainer = Ext.create('Ext.container.Container', {
        //border:false,
        //bodyBorder:false,
        width: '100%',
        height: '100%',
        layout: 'hbox',
        items: [{
                xtype: "container",
                layout: 'vbox',
                border: true,
                items: [{
                        xtype: 'container',
                        layout: 'hbox',
                        items: [{
                                xtype: "combobox",
                                id: 'dataSourceId',
                                fieldLabel: '数据源',
                                displayField: "name",
                                forceSelection: true,
                                editable: false,
                                valueField: 'id',
                                value: nowDataSource,
                                listeners: {
                                    change: function (obj, newValue, oldValue, eOpts) {
                                        nowDataSource = newValue
                                    }
                                },
                                store: {
                                    autoLoad: true,
                                    proxy: {
                                        type: 'ajax',
                                        url: '../datasource/store',
                                        reader: {
                                            type: 'json',
                                            root: 'results',
                                            totalProperty: 'total'
                                        }
                                    }
                                },
                                labelWidth: 50
                            },
                            {
                                xtype: "button",
                                text: '执行',
                                style: {
                                    marginRight: '10px'
                                },
                                handler: function () {
                                    Ext.Ajax.request({
                                        url: "../app/builddataset",
                                        params: {
                                            chartId: chartId,
                                            chartSql: sqlEditor.session.getValue(),
                                            dataSourceId: Ext.getCmp("dataSourceId").getValue()
                                        },
                                        success: function (response, opts) {
                                            var res = Ext.JSON.decode(response.responseText)
                                            console.log(res.success)
                                            if (res.success) {
                                                console.log(res.chartSql)
                                                window.chartSqlDis = res.chartSql
                                                var dimensions = []
                                                chartSource.dataset = {}
                                                var gridData = []
                                                var gridColumns = []
                                                var gridFields = []
                                                for (var i = 0; i < res.cols.length; i++) {
                                                    dimensions.push(res.cols[i])
                                                    gridColumns.push({
                                                        text: res.cols[i],
                                                        dataIndex: res.cols[i]
                                                    })
                                                }

                                                chartSource.dataset.dimensions = dimensions
                                                chartSource.dataset.source = res.rows

                                                if (chartSourceDis == "") {
                                                    chartSourceDis = formatSource(chartSource)
                                                }

                                                eval("var myOption = "+chartSourceDis)
                                                var chartSourceCopy = myOption
                                                chartSourceCopy.dataset = {}
                                                chartSourceCopy.dataset.dimensions = dimensions
                                                chartSourceCopy.dataset.source = res.rows
                                                chartSourceDis = formatSource(chartSourceCopy)


                                                dataSourceDataset = Ext.clone(chartSource.dataset)

                                                if (rowMode != null && rowMode) {
                                                    eval("var myOption = "+chartSourceDis)
                                                    var tobj = myOption
                                                    tobj.dataset = rowToColumn(dataSourceDataset)
                                                    chartSourceDis = JSON.stringify(tobj)
                                                    chartSource.dataset = rowToColumn(dataSourceDataset)
                                                }



                                                var gridStore = Ext.create('Ext.data.Store', {
                                                    //fields:[ 'name', 'email', 'phone'],
                                                    data: res.rows
                                                });

                                                nowDataSetPanel = {
                                                    xtype: 'grid',
                                                    width: '100%',
                                                    height: 311,
                                                    store: gridStore,
                                                    viewConfig: {
                                                        stripeRows: true,
                                                        enableTextSelection: true
                                                    },
                                                    columns: gridColumns
                                                }

                                                Ext.getCmp('dataSetPanel').show()
                                                Ext.getCmp('dataSetPanel').remove(0)
                                                Ext.getCmp('dataSetPanel').add(nowDataSetPanel)

                                                //temp = Ext.Object.merge(temp,chart1.getOption())
                                                eval("var myOption = "+chartSourceDis)
                                                chart1.setOption(myOption, {
                                                    notMerge: true
                                                })

                                                $('#sourceContent2').html(formatSource(chartSource))

                                            } else {
                                                nowDataSetPanel = {
                                                    xtype: 'container',
                                                    html: '<div style="color:red;font-size:20px">' + res.message + '</div>'
                                                }
                                                Ext.getCmp('dataSetPanel').show()
                                                Ext.getCmp('dataSetPanel').remove(0)
                                                Ext.getCmp('dataSetPanel').add(nowDataSetPanel)
                                            }

                                        },
                                        failure: function (response, opts) {}
                                    });
                                }
                            },
                            {
                                xtype: "button",
                                text: '复制执行代码',
                                handler: function () {
                                    console.log(window.chartSqlDis)
                                    Ext.toast('Sql复制成功：' + window.chartSqlDis);
                                    clipboard.writeText(window.chartSqlDis);
                                }
                            }

                        ]

                    },
                    //{xtype:"textareafield",id:'chartSql',fieldLabel:'Sql',labelWidth:50,height:200,width:'90%',value:chartSql},
                    {
                        xtype: "container",
                        id: 'chartSql',
                        height: 277,
                        width: '100%',
                        /*border: 1,
                        style: {
                            borderColor: 'red',
                            borderStyle: 'solid'
                        },*/
                        listeners: {
                            render: function () {
                                sqlEditor = ace.edit("sqlEditor");
                                sqlEditor.setOptions({
                                    //enableBasicAutocompletion: true,
                                    //enableSnippets: true,
                                    //enableBasicAutocompletion: true,
                                    // enableLiveAutocompletion: true
                                });
                                sqlEditor.setTheme("ace/theme/monokai")
                                sqlEditor.setFontSize(20)
                                sqlEditor.session.setMode("ace/mode/sql");
                                sqlEditor.on("change", function () {
                                    chartSql = sqlEditor.session.getValue()
                                });
                                sqlEditor.session.setValue(chartSql)
                                /*
                                var occurCommands = [{
                                    name: "occurexit",
                                    bindKey: 'esc|Ctrl-G',
                                    exec: function(editor) {
                                        
                                    },
                                    readOnly: true
                                }];
                                sqlEditor.commands.addCommands(occurCommands);
                                */
                            }
                        },
                        html: "<div id='sqlEditor'>" + chartSql + "</div>"
                    }
                ],
                width: '45%'
            },
            {
                xtype: "panel",
                height: '100%',
                title: '',
                width: '55%',
                //frame:true,
                border: 1,
                height: '100%',
                id: 'dataSetPanel',
                hidden: true,
                items: [


                ]
            }
        ]
    })


    var adapterStore = Ext.create('Ext.data.Store', {
        autoLoad: true,
        pageSize: 200,
        remoteSort: true,
        remoteFilter:true,
        listeners:{
            beforeload:function() {
                
            },
            load:function( obj, records, successful, operation, eOpts ) {
                for(var i=0;i<records.length;i++) {
                    if (nowRemoteAdapterId!=null && nowRemoteAdapterId==records[i].data.id) {
                        Ext.getCmp("remoteAdapterGrid").getSelectionModel().select(records[i])
                        break
                    }
                }
            }
        },
        proxy: {
            type: 'ajax',
            url : '../remoteadapter/store',
            reader: {
                type: 'json',
                root: 'results',
                totalProperty: 'total'
            }
        }
    });

    var remoteDataContainer = Ext.create('Ext.container.Container', {
        width: '100%',
        height: '100%',
        layout: 'hbox',
        items: [{
                xtype: 'container',
                layout: 'vbox',
                width: '45%',
                height: 309,
                items: [
                    {
                        xtype: 'container',
                        layout: 'hbox',
                        items:[
                            {
                                xtype: 'textfield',
                                value: nowRemoteUrl,
                                fieldLabel: 'Http地址',
                                id: 'dataRemoteUrl',
                                width: 400,
                                listeners: {
                                    change: function (obj, newValue, oldValue, eOpts) {
                                        nowRemoteUrl = newValue
                                    }
                                },
                                name: 'remoteData'
                            },
                            {
                                xtype: 'button',
                                text: '获取数据',
                                handler: function () {
        
                                    Ext.Ajax.request({
                                        url: "../app/getremotedata",
                                        params: {
                                            id: chartId,
                                            adapterSource:nowRemoteAdapterSource,
                                            url: Ext.getCmp('dataRemoteUrl').getValue()
                                        },
                                        success: function (response, opts) {
                                            var res = Ext.JSON.decode(response.responseText)
                                            if (res.success) {
                                                var dimensions = []
                                                chartSource.dataset = {}
                                                var gridData = []
                                                var gridColumns = []
                                                var gridFields = []
        
                                                if (res.results.size != 0) {
                                                    for (var i in res.results[0]) {
                                                        dimensions.push(i)
                                                        gridColumns.push({
                                                            text: i,
                                                            dataIndex: i
                                                        })
                                                    }
        
                                                }
                                                //for (var i=0;i<res.results.length;i++) {
                                                //    gridData.push()
                                                // }
                                                chartSource.dataset.dimensions = dimensions
                                                chartSource.dataset.source = res.results
                                                if (chartSourceDis == "") {
                                                    chartSourceDis = formatSource(chartSource)
                                                }
                                               
                                                eval("var myOption = "+chartSourceDis)
                                                var chartSourceCopy = myOption
                                                
                                                chartSourceCopy.dataset = {}
                                                chartSourceCopy.dataset.dimensions = dimensions
                                                chartSourceCopy.dataset.source = res.results
                                                chartSourceDis = formatSource(chartSourceCopy)
                                                var gridStore = Ext.create('Ext.data.Store', {
                                                    data: res.results
                                                });
                                                nowRemoteDataSetPanel = {
                                                    xtype: 'grid',
                                                    width: '100%',
                                                    height: 308,
                                                    store: gridStore,
                                                    viewConfig: {
                                                        stripeRows: true,
                                                        enableTextSelection: true
                                                    },
                                                    columns: gridColumns
                                                }
                                                Ext.getCmp('remoteDataSetPanel').show()
                                                Ext.getCmp('remoteDataSetPanel').remove(0)
                                                Ext.getCmp('remoteDataSetPanel').add(nowRemoteDataSetPanel)
                                                

                                                if (displayTable) {
                                                    if (nowTableTheme==null||nowTableTheme=="") {
                                                        renderDefaultTable(chartSourceCopy)
                                                    } else {
                                                        var html = ""
                                                        try {
                                                            html = baidu.template(nowTableThemeSource,
                                                                {
                                                                    rows:chartSourceCopy.dataset.source,
                                                                    cols:chartSourceCopy.dataset.dimensions
                                                                }
                                                            );  
                                                        } catch(e) {
                                                            console.log(e)
                                                        }
                                                        $('#chart1').html(html)
                                                    }
                                                } else {
                                                    var obj = nowChartThemeSource
                                                    echarts.registerTheme(nowChartThemeName, obj)
                                                    chart1 = echarts.init(document.getElementById('chart1'),nowChartThemeName);
                                                    try {
                                                        chart1.setOption(chartSourceCopy, {notMerge: true})
                                                    } catch (e) {
                                                        console.log(e)
                                                    }
                                                }

                                                
                                                $('#sourceContent2').html(formatSource(chartSource))
                                            } else {
                                                nowRemoteDataSetPanel = {
                                                    xtype: 'container',
                                                    html: '<div style="color:red;font-size:20px">' + res.message + '</div>'
                                                }
                                                Ext.getCmp('remoteDataSetPanel').show()
                                                Ext.getCmp('remoteDataSetPanel').remove(0)
                                                Ext.getCmp('remoteDataSetPanel').add(nowRemoteDataSetPanel)
                                            }
                                        }
                                    });
        
                                }
                            }
                        ]
                       
                    },
                  
                    {
                        xtype: 'grid',
                        title: '数据适配器',
                        id:'remoteAdapterGrid',
                        allowDeselect:true,
                        listeners:{
                            select:function(obj, record, index, eOpts) {
                                nowRemoteAdapterId = record.data.id
                                nowRemoteAdapterSource = record.data.adapter_source
                            },
                            deselect:function(obj, record, index, eOpts) {
                                nowRemoteAdapterId = null
                                nowRemoteAdapterSource = null
                            }
                        },
                        //frame: true,
                        width: '100%',
                        height: 311,
                        store: adapterStore,
                        viewConfig: {
                            stripeRows: true,
                            enableTextSelection: true
                        },
                        tbar: [
                            { 
                                xtype: 'button', text: '增加',iconCls:'x-fa fa-plus',
                                handler:function() {
                                    if (chartId==null||chartId=="") {
                                        alert("请先保存图表")
                                        return
                                    }
                                    openEditAdapterWindow('增加数据适配器')
                                    
                                } 
                            },
                            { 
                                xtype: 'button', text: '修改',iconCls:'x-fa fa-pencil',
                                handler:function() {
                                    if (chartId==null||chartId=="") {
                                        alert("请先保存图表")
                                        return
                                    }
                                    openEditAdapterWindow('修改数据适配器')
                                } 
                            },
                            { 
                                xtype: 'button', text: '删除',iconCls:'x-fa fa-minus',
                                handler:function() {
                                    if (chartId==null||chartId=="") {
                                        alert("请先保存图表")
                                        return
                                    }
                                    var id = Ext.getCmp('remoteAdapterGrid').getSelection()[0].data.id
                                    Ext.Ajax.request({
                                        url: "../remoteadapter/delete",
                                        params: {id:id},
                                        success:function(response, opts) {
                                            Ext.getCmp('remoteAdapterGrid').getStore().load()
                                        }
                                    })
                
                                }   
                            }
                        ],
                        columns: [
                            {
                                text: '适配器Id',
                                dataIndex: 'id'
                            },
                            {
                                text: '适配器名称',
                                flex:1,
                                dataIndex: 'adapter_name'
                            }
                        ]
                    }
                ]
            },
            {
                xtype: "panel",
                height: 310,
                title: '',
                width: '60%',
                border: 1,
                height: '100%',
                id: 'remoteDataSetPanel',
                hidden: true,
                items: []
            }

        ]
    })


    var dsTabs = Ext.create('Ext.tab.Panel', {
        //width: 400,
        //height: 400,
        listeners: {
            tabchange: function (tabPanel, newCard, oldCard, eOpts) {

                nowDsActiveTab = newCard.title
                //nowDsActiveTab
            }
        },
        items: [{
                title: 'Sql数据',
                items: sqlDsContainer
            },
            {
                title: '文件数据',

                items: {
                    xtype: 'form',
                    id: 'fileDataForm',
                    height: 309,
                    items: [{
                            xtype: 'filefield',
                            //emptyText: '选择文件',
                            name: 'excelFile',
                            fieldLabel: 'Excel文件',
                            width: 500,
                            //labelAlign:'right',
                            buttonText: '选择文件'
                        },
                        {
                            xtype: 'button',
                            text: '上传',
                            handler: function () {
                                console.log(Ext.getCmp('attrPanel').items.items[0])
                                var form = Ext.getCmp('fileDataForm')
                                if (form.isValid()) {
                                    form.submit({
                                        url: '../app/upload',
                                        waitMsg: '上传中...',
                                        success: function (fp, o) {
                                            console.log(o.result)
                                            Ext.toast({
                                                html: '上传成功！',
                                                title: '系统提示',
                                                width: 200,
                                                align: 't'
                                            });


                                            chartSource.dataset = {}
                                            chartSource.dataset.dimensions = o.result.cols
                                            chartSource.dataset.source = o.result.rows

                                            var chartSourceCopy = JSON.parse(chartSourceDis)
                                            chartSourceCopy.dataset = {}
                                            chartSourceCopy.dataset.dimensions = o.result.cols
                                            chartSourceCopy.dataset.source = o.result.rows
                                            chartSourceDis = JSON.stringify(chartSourceCopy)
                                            chart1.setOption(chartSourceCopy, {
                                                notMerge: true
                                            })

                                            $('#sourceContent2').html(formatSource(chartSource))

                                        }
                                    });
                                }
                                /*var form = this.lookupReference('firstForm').getForm();

                                if (form.isValid()) {
                                    form.submit({
                                        url: 'data/form/file-upload.php',
                                        waitMsg: 'Uploading your photo...',
                                        success: function(fp, o) {
                                            var tpl = new Ext.XTemplate(
                                                'File processed on the server.<br />',
                                                'Name: {fileName}<br />',
                                                'Size: {fileSize:fileSize}'
                                            );

                                            Ext.Msg.alert('Success', tpl.apply(o.result));
                                        }
                                    });
                                }*/
                            }
                        }
                    ]
                }
            },
            {
                title: '远程数据',
                items: remoteDataContainer
            }
        ]
    });



    Ext.getCmp('attrPanel').setTitle('数据源')
    Ext.getCmp('attrPanel').remove(0)
    Ext.getCmp('attrPanel').add(dsTabs)

    if (nowDsActiveTab == "Sql数据") {
        dsTabs.setActiveTab(0)
    }
    if (nowDsActiveTab == "文件数据") {
        dsTabs.setActiveTab(1)
    }
    if (nowDsActiveTab == "远程数据") {
        dsTabs.setActiveTab(2)
    }



    if (nowDataSetPanel != null) {
        Ext.getCmp('dataSetPanel').add(nowDataSetPanel)
        Ext.getCmp('dataSetPanel').setHidden(false)
    }

}